package cbs.jdtag.actions;

import java.awt.event.ActionEvent;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.filechooser.FileFilter;

import cbs.jdtag.AppContext;
import cbs.jdtag.DataModel2;
import cbs.jdtag.io.XMLWriter;

public class SaveAsAction extends AbstractAction {

	private static final long serialVersionUID = -8655747597916053456L;
	private transient final Logger logger = Logger.getLogger(this.getClass().getName());

	private final JFileChooser fd = new JFileChooser();
	
	public SaveAsAction() {
		super("Save as");
		
		putValue(Action.ACCELERATOR_KEY, KeyStroke.getKeyStroke(KeyEvent.VK_S, InputEvent.CTRL_MASK));
		
		fd.setFileFilter(new FileFilter() {
			@Override
			public String getDescription() {
				return "DTAG files (*.atag)";
			}
			
			@Override
			public boolean accept(File file) {
				if (file.getName().endsWith(".atag")) {
					return true;
				}
				else if (file.isDirectory()) {
					return true;
				}
				else {
					return false;
				}
			}});
		fd.setMultiSelectionEnabled(false);
		fd.setFileSelectionMode(JFileChooser.FILES_ONLY);
	}
	
	public void actionPerformed(ActionEvent ae) {
		DataModel2 dm = AppContext.getDM();
		
		logger.fine("Executing...");
		
		if (dm.saved == true) {
			AppContext.mainView.setStatusText("There is nothing to save right now.");
			return;
		}
		
		fd.setCurrentDirectory(new File(AppContext.getRecentlyUsedDir()));
		fd.setSelectedFile(dm.getAlignmentFile());
		int retVal = fd.showDialog(AppContext.mainView, "Save as");
		
		if (retVal == JFileChooser.APPROVE_OPTION) {
			
			AppContext.setRecentlyUsedDir(fd.getCurrentDirectory().getPath());
			
			File f = fd.getSelectedFile();
			if (f.exists()) {
				retVal = JOptionPane.showConfirmDialog(AppContext.mainView,
						"File \"" + f + "\" already exists. Overwrite?",
						"File exists",
						JOptionPane.YES_NO_OPTION);
				if (retVal != JOptionPane.OK_OPTION) {
					AppContext.mainView.setStatusText("File not saved.");
					return;
				}
			}
			
			try {
				XMLWriter.save(f);
				
				dm.setAlignmentFile(fd.getSelectedFile());
				AppContext.mainView.setTitle("jdtag: " + dm.getAlignmentFile());
				AppContext.mainView.setStatusText("File saved.");
			}
			catch (Exception e) {
				logger.log(Level.SEVERE, e.getLocalizedMessage(), e);
				JOptionPane.showMessageDialog(AppContext.mainView,
						e.getLocalizedMessage(), "Parse error",
						JOptionPane.ERROR_MESSAGE);
				AppContext.mainView.setStatusText("Parse error.");
				return;
			}
		}
	}
}
